package com.gzc.just.play.last.war.common.serializer;

import com.gzc.just.play.last.war.common.scanner.MessageDeserializerScanner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 基于自动扫描的消息反序列化器工厂
 * 使用MessageDeserializerScanner获取自动注册的反序列化器
 * 
 * 这是统一的反序列化器获取入口，所有消息反序列化都应该通过此类获取反序列化器
 */
@Component
public class AutoMessageDeserializerFactory extends MessageDeserializerFactory {
    private static final Logger logger = LoggerFactory.getLogger(AutoMessageDeserializerFactory.class);

    private static volatile MessageDeserializerScanner sharedScanner;

    public static void registerScanner(MessageDeserializerScanner scanner) {
        sharedScanner = scanner;
        logger.info("MessageDeserializerScanner registered for AutoMessageDeserializerFactory");
    }

    private static MessageDeserializerScanner requireScanner() {
        MessageDeserializerScanner scanner = sharedScanner;
        if (scanner == null) {
            throw new IllegalStateException("MessageDeserializerScanner has not been initialized yet");
        }
        return scanner;
    }
    
    /**
     * 静态方法：根据消息ID获取反序列化器
     * 这是统一的反序列化器获取入口
     * @param messageId 消息ID
     * @return 反序列化器，如果未注册则返回null
     */
    @SuppressWarnings("unchecked")
    public static <T> MessageDeserializer<T> getDeserializerStatic(int messageId) {
        MessageDeserializerScanner scanner = sharedScanner;
        if (scanner == null) {
            logger.warn("MessageDeserializerScanner not initialized, cannot get deserializer for messageId: {}", messageId);
            return null;
        }
        return scanner.getDeserializer(messageId);
    }
    
    /**
     * 静态方法：根据消息ID和模块获取反序列化器
     * @param messageId 消息ID
     * @param module 模块名称
     * @return 反序列化器，如果未注册则返回null
     */
    @SuppressWarnings("unchecked")
    public static <T> MessageDeserializer<T> getDeserializerStatic(int messageId, String module) {
        MessageDeserializerScanner scanner = sharedScanner;
        if (scanner == null) {
            logger.warn("MessageDeserializerScanner not initialized, cannot get deserializer for messageId: {} in module: {}", 
                       messageId, module);
            return null;
        }
        MessageDeserializer<T> deserializer = scanner.getDeserializer(messageId, module);
        if (deserializer != null) {
            return deserializer;
        }
        // 回退到全局查找
        return scanner.getDeserializer(messageId);
    }
    
    /**
     * 静态方法：检查是否有指定消息ID的反序列化器
     * @param messageId 消息ID
     * @return 是否已注册
     */
    public static boolean hasDeserializer(int messageId) {
        return getDeserializerStatic(messageId) != null;
    }
    
    private String moduleName;
    
    public AutoMessageDeserializerFactory() {
        // 默认模块名
        this.moduleName = "default";
    }
    
    public AutoMessageDeserializerFactory(String moduleName) {
        this.moduleName = moduleName;
    }
    
    /**
     * 设置模块名称
     */
    public void setModuleName(String moduleName) {
        this.moduleName = moduleName;
    }
    
    @Override
    public String getModuleName() {
        return moduleName;
    }
    
    @Override
    @SuppressWarnings("unchecked")
    public <T> MessageDeserializer<T> createDeserializer(int messageId) {
        MessageDeserializerScanner scanner = requireScanner();
        MessageDeserializer<T> deserializer = scanner.getDeserializer(messageId, moduleName);
        if (deserializer != null) {
            return deserializer;
        }
        
        return scanner.getDeserializer(messageId);
    }
    
    @Override
    public int[] getSupportedMessageIds() {
        Map<Integer, MessageDeserializer<?>> deserializers = requireScanner().getDeserializersForModule(moduleName);
        return deserializers.keySet().stream().mapToInt(Integer::intValue).toArray();
    }
    
    @Override
    public boolean supportsMessage(int messageId) {
        MessageDeserializerScanner scanner = requireScanner();
        Map<Integer, MessageDeserializer<?>> deserializers = scanner.getDeserializersForModule(moduleName);
        if (deserializers.containsKey(messageId)) {
            return true;
        }
        
        return scanner.getDeserializer(messageId) != null;
    }
    
    /**
     * 获取所有可用的反序列化器（包括模块级别和全局级别）
     */
    public Map<Integer, MessageDeserializer<?>> getAllDeserializers() {
        MessageDeserializerScanner scanner = requireScanner();
        Map<Integer, MessageDeserializer<?>> result = new HashMap<>(scanner.getDeserializersForModule(moduleName));
        Map<Integer, MessageDeserializer<?>> globalDeserializers = scanner.getAllDeserializers();
        
        for (Map.Entry<Integer, MessageDeserializer<?>> entry : globalDeserializers.entrySet()) {
            result.putIfAbsent(entry.getKey(), entry.getValue());
        }
        
        return result;
    }
}
